/**
 * Created by xiey on 2016/3/11.
 *
 * data: [object Array] // 静态数据
 * api: [object String] // 远程请求数据
 * param: [object Object] // 远程请求参数
 * displayField: [object String]
 * valueField: [object String]
 *
 */
as.run(['$templateCache', function ($templateCache) {
    var content = [];
    content.push('<div class="inline fields">');
    content.push('  <div ng-repeat="item in $ctrl.$data track by $index" class="field">');
    content.push('    <a-checkbox label="{{item.$$display}}" ng-model="item.model" name="{{::$ctrl.name}}" ng-change="$ctrl.change()"></a-checkbox>');
    content.push('  </div>');
    content.push('  <a-store api="{{$ctrl.api}}" params="$ctrl.param" ng-model="$ctrl.storeData" ng-change="$ctrl.storeChange()" state="$ctrl.loadState"></a-store>');
    content.push('  <a-loader show="$ctrl.loadState==1" size="mini"></a-loader>');
    content.push('</div>');
    $templateCache.put('checkbox/checkbox-group.html', content.join(''));
}]).controller('$$CheckboxGroupCtrl', [function () {
    var ctrl = this, display = '$$display', value = '$$value';
    ctrl.$data = [];
    ctrl.$onInit = function () {
        var initData = function () {
            ctrl.$data = [];
            ctrl.data.forEach(function (item, i) {
                var obj = {};
                obj[display] = !!ctrl.displayField ? item[ctrl.displayField] : item;
                obj[value] = !!ctrl.valueField ? item[ctrl.valueField] : item;
                ctrl.$data[i] = obj;
            });
        };
        var initChoose = function () {
            ctrl.$data.forEach(function (item) {
                ctrl.model.$modelValue && ctrl.model.$modelValue.some(function (v) {
                    return item.model = item[value] === v;
                });
            });
        };
        ctrl.storeChange = function () {
            if (!ctrl.storeData) {
                ctrl.data = [];
                return;
            }
            ctrl.data = ctrl.storeData.data;
            initData();
            initChoose();
        };
        ctrl.model.$render = function () {
            initChoose();
        };
        ctrl.change = function () {
            var result = [];
            ctrl.$data.forEach(function (item) {
                if (item.model) {
                    result.push(item[value]);
                }
            });
            ctrl.model.$setViewValue(result);
        };
        if (!ctrl.api) {
            initData();
        }
    };
}]).component('aCheckboxGroup', {
    require    : {
        model: 'ngModel'
    },
    bindings   : {
        data        : '=?',
        api         : '@?',
        param       : '<',
        displayField: '@?',
        valueField  : '@?',
        name        : '@?'
    },
    templateUrl: 'checkbox/checkbox-group.html',
    controller : '$$CheckboxGroupCtrl'
});